﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UIListContainer : MonoBehaviour
{
    public RectTransform MaskContent;
    public ScrollRect Scroll;
    public RectTransform RtContent;

    protected List<UIListCell> mCells;
    protected XObjectPool mPool = new XObjectPool();

    public int Count { get { return mCells == null ? 0 : mCells.Count; } }

    private bool inited;
    private void Awake()
    {
        onInit();
    }

    private void onInit()
    {
        if (inited) return;
        inited = true;
        if (MaskContent == null)
            MaskContent = GetComponent<RectTransform>();
        if (Scroll == null)
            Scroll = GetComponent<ScrollRect>();
        if (RtContent == null)
            RtContent = transform.GetChild(0).GetComponent<RectTransform>();
        if (Scroll.content == null)
            Scroll.content = RtContent;

        Scroll.onValueChanged.AddListener(onScrollChanged);
    }

    private void OnDestroy()
    {
        if (mCells != null)
        {
            foreach (var tmp in mCells)
            {
                tmp.clear();
            }
        }
        MaskContent = null;
        Scroll = null;
        RtContent = null;
        mCells = null;
        mPool = null;
    }

    private void onScrollChanged(Vector2 vec)
    {
        if (mCells == null)
            return;
        display();
    }

    protected virtual void setAnchor()
    {
    }

    public virtual void display()
    {
    }

    public virtual void setDatas(List<UIListCell> cells)
    {
        onInit();

        // 如果是相同的数据 不需要做任何操作
        if (mCells == cells)
            return;

        if (mCells != null)
        {
            foreach (var tmp in mCells)
            {
                tmp.clear();
            }
        }

        mCells = cells;

        var index = 0;
        foreach (var tmp in mCells)
        {
            tmp.setPool(mPool);
            tmp.setIndex(index++);
        }

        setAnchor();
    }

    public void goToIndex(int index)
    {
        if (index < 0 || index >= mCells.Count)
        {
            return;
        }
        moveToIndex(index);
        display();
    }

    protected virtual void moveToIndex(int index)
    {
    }

    public void stopMovement()
    {
        Scroll.StopMovement();
    }
}